package cn.car.service.remote.process.Impl;

import cn.car.domains.dto.*;
import cn.car.domains.entity.VehicleBlackInfoEntity;
import cn.car.domains.entity.VehicleBlackPassInfoEntity;
import cn.car.domains.entity.VehicleControlInfoEntity;
import cn.car.domains.enums.SyncInfoCodeEnum;
import cn.car.exception.CarAccessControlException;
import cn.car.service.VehicleBlackInfoService;
import cn.car.service.VehicleBlackPassInfoService;
import cn.car.service.VehicleControlInfoService;
import cn.car.service.remote.TjRemoteService;
import cn.car.service.remote.process.Processor;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class SyncProcessor implements Processor {

    @Resource
    private TjRemoteService tjRemoteService;

    @Resource
    private VehicleBlackPassInfoService vehicleBlackPassInfoService;

    @Resource
    private VehicleBlackInfoService vehicleBlackInfoService;

    @Resource
    private VehicleControlInfoService vehicleControlInfoService;


    @Override
    public void process(BaseResponse response) {
        SyncInfoDto syncInfoDto = (SyncInfoDto) response;

        String syncCode = syncInfoDto.getSyncCode();
        if (null == syncCode) {
            log.info("[SyncProcessor] syncCode is null");
            return;
        }
        SyncInfoCodeEnum syncInfoCodeEnum = null;
        try {
            syncInfoCodeEnum = SyncInfoCodeEnum.valueOf(syncCode);
        } catch (IllegalArgumentException e) {
            throw CarAccessControlException.PARAMS_ERROR.newInstance("syncCode param error:{}", syncCode);
        }

        switch (syncInfoCodeEnum) {
            case B01 -> handleB01();
            case B02 -> handleB02();
            case C01 -> handleC01();
            case S01 -> log.info("[SyncProcessor] current sync is S01");
        }
    }

    private void handleC01() {
        try {
            ControlStrategyDto controlStrategy = tjRemoteService.getControlStrategy();
            if (!"200".equals(controlStrategy.getCode())) {
                log.error("[SyncProcessor] remote control strategy is error");
            }

            log.info("controlStrategy:{}", JSONObject.toJSONString(controlStrategy));
            // 1.消息入库
            VehicleControlInfoEntity vehicleControlInfoEntity = new VehicleControlInfoEntity();
            vehicleControlInfoEntity.setAlarmLevel(controlStrategy.getAlarmLevel());
            vehicleControlInfoEntity.setResponseLevel(controlStrategy.getResponseLevel());
            vehicleControlInfoEntity.setControlMethod(controlStrategy.getControlMethod());
            vehicleControlInfoEntity.setAlarmStTime(DateUtil.parse(controlStrategy.getAlarmStTime(), DatePattern.NORM_DATETIME_PATTERN).getTime());
            vehicleControlInfoEntity.setAlarmEndTime(DateUtil.parse(controlStrategy.getAlarmEndTime(), DatePattern.NORM_DATETIME_PATTERN).getTime());
            vehicleControlInfoService.insert(vehicleControlInfoEntity);

            // 2.推送到前端
        } catch (IOException e) {
            log.error("[handleC01] error e" + e);
        }
    }

    private void handleB02() {
        try {
            VehicleBlackDtoList vehicleBlackDtoList = tjRemoteService.getBlackVehicleInfos();
            if (!"200".equals(vehicleBlackDtoList.getCode())) {
                log.error("[SyncProcessor] remote black vehicle infos is error");
            }
            log.info("vehicleBlackDtoList:{}", JSONObject.toJSONString(vehicleBlackDtoList));
            List<VehicleBlackDto> vehicleBlackDTOs = vehicleBlackDtoList.getVehicleBlackDtoList();
            if (CollectionUtil.isEmpty(vehicleBlackDTOs)){
                return;
            }
            List<VehicleBlackInfoEntity> vehicleBlackInfoEntityList = buildVehicleBlackInfoEntity(vehicleBlackDTOs);

            for (VehicleBlackInfoEntity vehicleBlackInfoEntity : vehicleBlackInfoEntityList) {

                List<VehicleBlackInfoEntity> vehicleBlackInfoEntities = vehicleBlackInfoService.queryByVehicleNumber(vehicleBlackInfoEntity.getVehicleNumber());
                if (CollectionUtil.isEmpty(vehicleBlackInfoEntities)){
                    vehicleBlackInfoService.save(vehicleBlackInfoEntity);
                } else {
                    vehicleBlackInfoService.update(vehicleBlackInfoEntity);
                }
            }

        } catch (IOException e) {
            log.error("[handleB02] error e" + e);
        }
    }

    private List<VehicleBlackInfoEntity> buildVehicleBlackInfoEntity(List<VehicleBlackDto> vehicleBlackDTOs) {
        List<VehicleBlackInfoEntity> vehicleBlackInfoEntityList = new ArrayList<>();
        for (VehicleBlackDto vehicleBlackDto : vehicleBlackDTOs) {

            VehicleBlackInfoEntity vehicleBlackInfoEntity = BeanUtil.toBean(vehicleBlackDto, VehicleBlackInfoEntity.class);
            vehicleBlackInfoEntity.setIssueTime(DateUtil.parse(vehicleBlackDto.getIssueTime(), DatePattern.PURE_DATE_PATTERN).getTime());
            vehicleBlackInfoEntity.setReleaseTime(DateUtil.parse(vehicleBlackDto.getReleaseTime(), DatePattern.PURE_DATE_PATTERN).getTime());
            vehicleBlackInfoEntity.setVehicleNumber(vehicleBlackDto.getPlateNo());
            vehicleBlackInfoEntity.setVehiclePlateColor(vehicleBlackDto.getPlateColor());
            vehicleBlackInfoEntityList.add(vehicleBlackInfoEntity);
        }

        return vehicleBlackInfoEntityList;
    }

    private void handleB01() {
        try {
            VehicleBlackPassDtoList blackVehiclePassInfos = tjRemoteService.getBlackVehiclePassInfos();
            if (!"200".equals(blackVehiclePassInfos.getCode())) {
                log.error("[SyncProcessor] remote black vehicle pass infos is error");
            }
            log.info("blackVehiclePassInfos:{}", JSONObject.toJSONString(blackVehiclePassInfos));
            List<VehicleBlackPassDto> vehicleBlackPassDtoList = blackVehiclePassInfos.getVehicleBlackPassDtoList();
            if (CollectionUtil.isEmpty(vehicleBlackPassDtoList)){
                return;
            }
            List<VehicleBlackPassInfoEntity> vehicleBlackPassInfoEntityList = buildVehicleBlackPassInfoEntity(vehicleBlackPassDtoList);
            vehicleBlackPassInfoEntityList.forEach(vehicleBlackPassInfoEntity ->
                    vehicleBlackPassInfoService.save(vehicleBlackPassInfoEntity));

        } catch (IOException e) {
            log.error("[handleB01] error e" + e);
        }
        
    }

    private List<VehicleBlackPassInfoEntity> buildVehicleBlackPassInfoEntity(List<VehicleBlackPassDto> vehicleBlackPassDtoList) {

        List<VehicleBlackPassInfoEntity> vehicleBlackPassInfoEntityList = new ArrayList<>();
        for (VehicleBlackPassDto vehicleBlackPassDto : vehicleBlackPassDtoList) {

            VehicleBlackPassInfoEntity vehicleBlackPassInfoEntity = BeanUtil.toBean(vehicleBlackPassDto, VehicleBlackPassInfoEntity.class);
            vehicleBlackPassInfoEntity.setInTime(DateUtil.parse(vehicleBlackPassDto.getInTime(), DatePattern.NORM_DATETIME_PATTERN).getTime());
            vehicleBlackPassInfoEntity.setOutTime(DateUtil.parse(vehicleBlackPassDto.getOutTime(), DatePattern.NORM_DATETIME_PATTERN).getTime());
            vehicleBlackPassInfoEntity.setVehicleNumber(vehicleBlackPassDto.getPlateNo());
            vehicleBlackPassInfoEntity.setVehiclePlateColor(vehicleBlackPassDto.getPlateColor());
            vehicleBlackPassInfoEntityList.add(vehicleBlackPassInfoEntity);
        }

        return vehicleBlackPassInfoEntityList;

    }
}
